<template>
  <div id="map-container"></div>
</template>
<script setup>
import { onMounted, onUnmounted } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { useRoute } from "vue-router";
let map = null;
onMounted(() => {
  const route = useRoute();
  const startLng = parseFloat(route.query.startLng) || 0; // 转成数字，没值时给默认值
  const startLat = parseFloat(route.query.startLat) || 0;
  const endLng = parseFloat(route.query.endLng) || 0;
  const endLat = parseFloat(route.query.endLat) || 0;
  window._AMapSecurityConfig = {
    securityJsCode: "a5ae4f2c3e80ec9ee1368c959f783b9e"
  };
  AMapLoader.load({
    key: "504068c978b5529d39cad8260cdf1326",
    version: "2.0",
    plugins: ["AMap.Scale", "AMap.Driving",]// 引入路线规划插件
  })
  .then((AMap) => {
      map = new AMap.Map("map-container", {
        viewMode: "2D",
        zoom: 12,
        center: [parseFloat(startLng), parseFloat(startLat)] // 根据经纬度设置地图中心点
      });
      var scaleControl = new AMap.Scale({
        position :'RB',
      });
      map.addControl(scaleControl);
      var data = [[parseFloat(startLng),parseFloat(startLat)],[parseFloat(endLng),parseFloat(endLat)]];//创建一个起点，目标地点
      // 构造路线导航类
      var driving = new AMap.Driving({
        map: map
      });
      // 根据起终点经纬度规划驾车导航路线
      driving.search(convertLatLng(data[0]), convertLatLng(data[1]));
      function convertLatLng(LngLat) {
        return new AMap.LngLat(LngLat[0], LngLat[1]);
      }
    })
  .catch((e) => {
      console.error('地图加载失败:', e);
    });
});
onUnmounted(() => {
  map?.destroy();
});
</script>
<style scoped>
#map-container{
  padding:0px;
  margin: 0px;
  width: 100%;
  height: 830px;
  overflow: hidden;
  position: relative;
}
</style>
